package com.tedu.egcqmvcboot.exception;

import com.tedu.egcqmvcboot.result.JsonResult;
import com.tedu.egcqmvcboot.result.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException e) {
        System.out.println("参数校验失败");
        return new JsonResult(Status.VALIDATE_ERROR);
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e){
        String message=e.getMessage();//findById.id:微博ID必须在1-99999之间
        message=message.substring(message.indexOf(":")+1).trim();
        log.warn(message,e);
        return new JsonResult(Status.VALIDATE_ERROR,message);
    }
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message=e.getFieldError().getDefaultMessage();
        log.warn(message,e);
        return new JsonResult(Status.VALIDATE_ERROR,message);
    }



}
